<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :needReturn="false"
      :btnList="fullInfo.btnList"
      :newFullScreenClass="newFullScreenClass"
    >
      <div id="table-list">
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <BasicInformation :info="infoList" />
          </div>
        </div>

        <div class="model-panel" id="table-box">
          <div class="model-panel-title">
            <p>{{ $t('detailInfo') }}</p>
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <PageFilter
              v-model:query="filterInfo.query"
              :filter-btn="filterInfo.list"
            >
              <template v-slot:filter-selectMode>
                <el-select
                  @change="getList"
                  clearable
                  v-model="filterInfo.query.queryParams.selectMode"
                >
                  <el-option
                    :value="item.code"
                    v-for="(item, index) in filterInfo.data.selectModeOption"
                    :key="index"
                    :label="item.name"
                  />
                </el-select>
              </template>
            </PageFilter>
            <div class="flex_full_item">
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <!-- 表格 -->
                <PageTable
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :index-method="indexMethod"
                  :row-class-name="rowClassName"
                  :check-box="false"
                  :highlight-row="false"
                  :tab-index="true"
                  :summary="true"
                  :summaryFieldList="tableInfo.summaryFieldList"
                  :summaries-fn="getSummaries"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="false"
                >
                  <template v-slot:col-licenseNumber="scope">
                    <p>{{ scope.row.licenseNumber || '-' }}</p>
                    <p>{{ scope.row.brandName || '-' }}</p>
                  </template>
                  <template v-slot:col-commonName="scope">
                    <p>{{ scope.row.commonName || '-' }}</p>
                    <p>{{ scope.row.productCode || '-' }}</p>
                    <p>{{ scope.row.alias || '-' }}</p>
                  </template>
                  <template v-slot:col-type="scope">
                    <p>{{ scope.row.productTypeValue || '-' }}</p>
                    <p>{{ scope.row.codeTypeValue || '-' }}</p>
                    <p>{{ scope.row.productCategoryValue || '-' }}</p>
                  </template>
                  <template v-slot:col-standard="scope">
                    <p>{{ scope.row.standard || '-' }}</p>
                    <p>{{ scope.row.unitName || '-' }}</p>
                  </template>
                </PageTable>
              </el-form>
              <p v-if="loading">加载中...</p>
            </div>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <individual-details
      v-if="individualDetailsInfo.visible"
      v-model:show-dialog="individualDetailsInfo.visible"
      :api="individualDetailsInfo.api"
      :tableKey="individualDetailsInfo.tableKey"
      v-model:query="individualDetailsInfo.query"
      :info="individualDetailsInfo.productInfo"
    ></individual-details>
  </div>
</template>

<script setup name="dataEntryDetails">
import {
  getSubInventoryOrderDetailCustomizeListAll,
  subInventoryOrderExcel,
  getSubInventoryOrderPrint,
  subInventoryOrderDetailDiffAll,
} from '@/api/stock'
import IndividualDetails from './IndividualDetails'

import { getCustomizeSetting } from '@/api/customize'
import { fatchTemplateByCode } from '@/api/base'
import _ from 'lodash'

const { proxy } = getCurrentInstance()

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: () => {
      return ''
    },
  },
  tableRow: {
    type: Object,
    default: () => {
      return {}
    },
  },
})
const loading = ref(false)
const oldDataIndex = ref(-1)
const box = ref(undefined)

// 过滤相关配置
const fullInfo = ref({
  btnList: [
    { label: '打印', event: print, show: true },
    { label: '导出excel', event: exportExcel, show: true },
    { label: '返回', event: returnBank, show: true },
  ],
})
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      subOrderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.tableRow.id,
      },
    },
    queryParams: {
      selectMode: '',
    },
  },
  data: {
    selectModeOption: proxy.$store.state.permission.dict['selectMode'] || [],
  },
  list: [
    {
      label: '筛选条件',
      value: 'selectMode',
      type: 'slot',
    },
  ],
})
const infoList = ref({
  data: props.tableRow,
  fieldList: [
    { label: '房间号', value: 'roomNo' },
    { label: '创建人', value: 'createUserName' },
    { label: '创建时间', value: 'createTime' },
    { label: '盘点人', value: 'inventoryUserName' },
    { label: '盘点时间', value: 'inventoryTime' },
  ],
})
// 表格相关
const tableInfo = ref({
  ref: null,
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'stockQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'diffQty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'price', show: 'false' },
    { value: 'diffSumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: singleProductDetails,
        show: true,
      },
    ],
  },
})
const individualDetailsInfo = ref({
  query: {
    subOrderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: null,
    },
  },
  selectObj: {},
  visible: false,
  productInfo: {},
  api: getSubInventoryOrderDetailCustomizeListAll,
  tableKey:
    'wmsStockInventorySubDataEntryIndividualDetails-com.slip.spd.entity.vo.stock.SubInventoryOrderDetailVO',
})
const singleProductIndex = ref(0)
const count = ref(0)
const list = ref('')
const newFullScreenClass = ref('scrollY' + new Date().getTime())
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((item, index) => {
        item.tableIndex = index + 1
      })
    }
  },
  {
    deep: true,
  }
)

const showDialog = computed({
  get() {
    return props.visible
  },
  set(val) {
    proxy.$emit('update:visible', val) // 更新父组件visible
  },
})

onMounted(() => {
  box.value = document.getElementsByClassName(newFullScreenClass.value)[0]
  box.value && box.value.addEventListener('scroll', throttle(handleScroll, 30))
})
onBeforeUnmount(() => {
  box.value &&
    box.value.removeEventListener('scroll', throttle(handleScroll, 30))
})

function handleScroll() {
  // 获取eagleMapContainer的真实高度
  const box = document.getElementsByClassName(newFullScreenClass.value)[0]
  const boxHeight = box.offsetHeight
  // 获取table_list的真实高度（浮动内容的真实高度）
  const tableHeight = document.getElementById('table-list').offsetHeight
  const tableDom = document.getElementById('table-box')
  // boxHeight和滑块浮动的高度相差小于50 && 不在加载中 && 不是最后一页
  if (
    tableHeight - (box.scrollTop + boxHeight) < 50 &&
    !loading.value &&
    listPage.value + 1 < tableInfo.value.data.length / 50
  ) {
    // 第一次触发时，记录滑块高度
    // data里scrollTop，listPage默认为0
    if (!scrollTop.value) {
      scrollTop.value = box.scrollTop
    }
    // 触发下拉加载更多
    queryMoreStat(true, tableHeight, boxHeight)
  } else if (box.scrollTop <= tableDom.offsetTop + 200 && !loading.value) {
    // 如果滑块上拉到顶部，则向上加载50条
    queryMoreStat(false, tableHeight, boxHeight)
  }
}
function queryMoreStat(type, tableHeight, boxHeight) {
  loading.value = true
  // 触底加载
  const tableData = tableInfo.value.data
  if (type) {
    listPage.value = listPage.value + 1
    const centerPage = listPage.value * 50
    const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
    const endPage = centerPage + 50
    const newList = tableData.slice(startPage, endPage)
    if (listPage.value > 0) {
      const box = document.getElementsByClassName(newFullScreenClass.value)[0]
      // 视图跳到触发的数据，补回50的高度差值
      box.scrollTop = scrollTop.value - 50
    }
    tableInfo.value.list = newList
  } else {
    // 置顶加载
    if (listPage.value > 0) {
      listPage.value = listPage.value - 1
      const centerPage = listPage.value * 50
      const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
      const endPage = centerPage + 50
      const newList = tableData.slice(startPage, endPage)
      if (listPage.value > 0) {
        const tableDom = document.getElementById('table-box')
        const box = document.getElementsByClassName(newFullScreenClass.value)[0]
        // box.scrollTop = tableHeight - scrollTop.value - boxHeight

        box.scrollTop = tableDom.offsetTop + 220
      }
      tableInfo.value.list = newList
    } else {
      tableInfo.value.list = tableData.slice(0, 50)
    }
  }
  proxy.$nextTick(() => {
    loading.value = false
  })
}

function indexMethod(row) {
  // const centerPage = listPage.value * 50
  // const startPage = centerPage >= 50 ? centerPage - 50 : centerPage
  // return startPage + index + 1;
  return row.tableIndex
}

function getSummaries({ columns, data }) {
  const sums = []
  const tableData = tableInfo.value.data
  const summaryFieldList = tableInfo.value.summaryFieldList
  if (summaryFieldList.length === 0) return sums
  columns.forEach((column, index) => {
    let arrIndex = -1
    if (typeof summaryFieldList[0] === 'string') {
      arrIndex = _.findIndex(summaryFieldList, column.property)
    } else if (typeof summaryFieldList[0] === 'object') {
      arrIndex = _.findIndex(summaryFieldList, function (o) {
        return o.value === column.property
      })
    }
    if (arrIndex !== -1) {
      const values = tableData.map((item) => Number(item[column.property]))
      let formatter = summaryFieldList[arrIndex].formatter || ''
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!isNaN(value)) {
            if (formatter) {
              return proxy.$fn.accAdd(
                proxy.$fn.TripartiteReturnNumber(formatter(prev)),
                proxy.$fn.TripartiteReturnNumber(formatter(curr))
              )
            } else {
              return proxy.$fn.accAdd(prev, curr)
            }
          } else {
            return prev
          }
        }, 0)
        if (formatter) {
          sums[index] = formatter(sums[index])
        }
      } else {
        sums[index] = ''
      }
    }
  })
  // if (checkBox.value) {
  //   sums[1] = "合计";
  // } else {
  sums[0] = '合计'
  // }
  return sums
}

function debounce(fn, delay) {
  let timer = null
  return function () {
    if (timer !== null) {
      clearTimeout(timer)
    }
    timer = setTimeout(fn, delay)
  }
}
function throttle(fn, delay) {
  let timer = null,
    startTime = new Date()
  return function () {
    let curTime = new Date()
    let remaining = delay - (curTime - startTime)
    clearTimeout(timer)
    if (remaining <= 0) {
      startTime = new Date()
      fn.apply(proxy, arguments)
    } else {
      timer = setTimeout(fn, remaining)
    }
  }
}

function singleProductDetails(row) {
  individualDetailsInfo.value.productInfo = JSON.parse(JSON.stringify(row))
  individualDetailsInfo.value.query.subOrderId.value = props.tableRow.id
  if (Object.values(individualDetailsInfo.value.selectObj).length) {
    for (let key in individualDetailsInfo.value.selectObj) {
      individualDetailsInfo.value.selectObj[key].value = row[key]
    }
  } else {
    individualDetailsInfo.value.selectObj['depotStockId'] = {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: row.depotStockId,
    }
  }
  individualDetailsInfo.value.query = {
    ...individualDetailsInfo.value.query,
    ...individualDetailsInfo.value.selectObj,
  }
  individualDetailsInfo.value.visible = true
}
// 获取列表
function getList() {
  getSubInventoryOrderDetailCustomizeListAll(filterInfo.value.query).then(
    (resp) => {
      if (resp && resp.success) {
        tableInfo.value.data = resp.data
        list.value = tableInfo.value.data.slice(0, 50)
      }
    }
  )
}
// 搜索
function search() {
  //搜索
  const search = filterInfo.value.data.keyword
  if (search) {
    list.value = tableInfo.value.data.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'commonName') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'productCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'alias') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
  } else {
    list.value = tableInfo.value.data.slice(0, 50)
  }
}

function rowClassName({ row }) {
  let className = 'row' + row.id
  if (row.depotStockId === -2) {
    className += ' warning-row'
  }
  return className
}
function returnBank() {
  showDialog.value = false
  proxy.$emit('callback', true)
}
function getDifference() {
  subInventoryOrderDetailDiffAll(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data
      list.value = tableInfo.value.data.slice(0, 50)
    }
  })
}
function print() {
  fatchTemplateByCode({
    resourceCode: 'goodsLocationInventory:printSub',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp)
    }
  })
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'wmsStockInventorySubDataEntry-com.slip.spd.entity.vo.stock.SubInventoryOrderDetailVO',
    orderIds: [props.tableRow.id],
    queryParams: filterInfo.value.query.queryParams,
  }
  getSubInventoryOrderPrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(
        temp,
        newData,
        !proxy.$permission('goodsLocationInventory:price')
      )
    }
  })
}
function exportExcel() {
  subInventoryOrderExcel(filterInfo.value.query).then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'wmsStockInventorySubDataEntry-com.slip.spd.entity.vo.stock.SubInventoryOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      let obj = {}
      filterInfo.value.query.customizeUserVO = data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          obj[key] = {
            queryType: 'EQUALS',
            queryCategory: 'AND',
            ignoreEmptyValue: false,
            value: null,
          }
        }
      }
      individualDetailsInfo.value.selectObj = obj
      tableInfo.value.api = getSubInventoryOrderDetailCustomizeListAll
      getList()
    }
  })
}

let obj = {
  price: {
    label: '单价',
    value: 'price',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('goodsLocationInventory:price'),
    show: false,
    hidden: true,
  },
  diffSumAmount: {
    label: '盘点差异金额',
    value: 'diffSumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('goodsLocationInventory:price'),
    show: false,
    hidden: true,
  },
  sumAmount: {
    label: '盘点金额',
    value: 'sumAmount',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('goodsLocationInventory:price'),
    show: false,
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    permission: !proxy.$permission('goodsLocationInventory:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
})
getCustomize()
</script>

<style scoped lang="scss">
:deep(.el-table) .warning-row {
  background: #f5e4e4;
}
</style>
